观察者模式 -- 发布订阅模式

  • 观察者模式 : 一个对象(称为 subject )维持一系列依赖于它( 观察者 )的对象,将有关状态的任何变动自动通知给他们,来通过代码实现一个现实生活中的例子 : 听到孩子哭了,他爸去喂奶,她妈跑路 的例子,
    整个过程而言,首先,孩子要哭,哭了之后,她爸妈都听见,听见之后,她爸妈做出不同的反应.这种反应就是 : 他爸去喂奶,她妈跑路

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    class Son {
    constructor( dad, mom ) {
    this.dad = dad;
    this.mom = mom;
    this.cry = () => {
    console.log( '孩子哭了' );
    this.dad.notice();
    this.mom.notice();
    };
    }
    }

    class Father {
    constructor() {
    this.notice = () => {
    console.log( '他爸听到孩子哭了' );
    this.food();
    };
    this.food = () => {
    console.log( '他爸要去喂奶了' );
    };
    }
    }

    class Mother {
    constructor() {
    this.notice = () => {
    console.log( '她妈听到孩子哭了' );
    this.goAway();
    };
    this.goAway = () => {
    console.log( '她妈跑路了' );
    };
    }
    }

    let father = new Father();
    let mother = new Mother();
    let son = new Son( father, mother );
    setTimeout( function () {
    son.cry();
    }, 500 );

    输出结果为 :

    1
    2
    3
    4
    5
    孩子哭了
    他爸听到孩子哭了
    他爸要去喂奶了
    她妈听到孩子哭了
    她妈跑路了
文章目录